#include <iostream>
#include<fstream>
#include<string>
#include<regex>//正则式库
using namespace std;
// generate a random number between min and max
int random(int min, int max)
{
    return min + rand() % (max - min + 1);
}

// generate a Chinese phone
string generatePhone()
{
    string phone = "";
    for (int i = 0; i < 11; i++)
    {
        if (i == 0)
        {
            int erro=random(0,3);   
            if(erro>=2)//生成错误号码开头
            {
                phone += "5";
            }
            else
            {
                phone += "1";
            }
            
        }
        else if (i == 1)
        {
            int num=random(1,8);
            if(num<=2){phone += "3";}
            else if(num>2&&num<=4){phone += "5";}
            else if(random(1,8)>=7){phone += "7";}
            else {phone += "8";}
        }//前两位为13||15||17||18
        else//后面9位随机生成
        {
            phone += to_string(random(0, 9));
        }
    }
    return phone;
}
//greate a Chinese ID number
string generateIdNumber(){
    string idNumber = "";
    for(int i = 0; i < 18; i++){
        if(i == 0){
            idNumber += "1";
        }
        else if(i == 2){
            idNumber += "4";
        }
        else if(i == 6){
            idNumber += "2";
        }
        else if(i == 10){
            idNumber += "3";
        }
        else if(i == 14){
            idNumber += "5";
        }
        else{
            idNumber += to_string(random(0, 9));
        }
    }
    return idNumber;
}

void identifyPhone(string str,string& phone)//引用传递Phone
{
    string phoneNumber("\\b(1)([3,5,7,8][0-9]|[4578]5|[5-9]6)(\\d{4})(\\d{4})\\b");//识别规则,前两位为13、15、17、18并且11位
    regex r(phoneNumber);
    for (sregex_iterator it(str.begin(), str.end(), r), end_it;it != end_it;++it) //符合识别规则的
    {
        phone += it->str();
        phone +='\n';
    }
}
void identifyID(string str,string& ID)//引用传递ID
{
    string IDNumber("\\b(1)\\d([4])\\d{3}([2])\\d{3}([3])\\d{3}([5])\\d{2}(\\d|X)");//识别规则,18位
    regex r(IDNumber);
    for (sregex_iterator it(str.begin(), str.end(), r), end_it;it != end_it;++it) //符合识别规则的
    {
        ID += it->str();
        ID +='\n';
    }
}
int main() {
    /*int Call[11];//用来存储每一位号码
    ofstream w;
    w.open("Mydata.txt", ios::out | ios::trunc|ios::binary);//out写出去，trunc覆盖写入
    //f,open("Mydata.txt".ios::out,ios::app);在原来的基础上继续写入
    for (int num = 0; num < 11; num++)
    {
        w << "电话号码："<<generatePhone()<<"  身份证："<< generateIdNumber()<<endl;
    }
    w.close();//关闭f文件*/
    ifstream r;
    r.open("Mydata.txt",ios::in|ios::binary);
    if(!r.is_open())
    {
        cout<<"打开文件失败";
    }
    string s,res;
    while(!r.eof())
    {
        getline(r, s);//逐行读入文件
        res+=s;//逐行保存
        res+='\n';//换行
    }
    r.close();//关闭文件
    string Phone,ID;
    identifyPhone(res,Phone);//使用正则式识别电话号码
    identifyID(res,ID);//使用正则式识别身份证号码
    cout<<"txt:"<<'\n'<<res;
    cout<<"Phone:"<<'\n'<<Phone;
    cout<<"ID:"<<'\n'<<ID<<endl;
}
